package com.gitee.huanminabc.utils_common.file;

import com.gitee.huanminabc.jcommon.exception.CommonException;
import info.monitorenter.cpdetector.io.*;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;

/**
 * @description:
 * @author: huanmin
 * @create: 2025-04-03 11:48
 **/
public class FileCodingUtil {


    //文件编码获取
    public static String getFileCharsetName(File file) {
        try {
            if( file.length()==0){
                throw new RuntimeException("文件长度为0,无法获取编码");
            }
            // 获取 CodepageDetectorProxy 实例
            CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
            // 添加解析器，会使用到添加的后 2 个 ext 里的 jar 包
            detector.add(new ParsingDetector(false));
            detector.add(JChardetFacade.getInstance());
            detector.add(ASCIIDetector.getInstance());
            detector.add(UnicodeDetector.getInstance());
            Charset charset = detector.detectCodepage(file.toURI().toURL());
            if (charset != null) {
                return charset.name();
            } else {
                return null;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 文件编码转换  ,将当前文件的编码转换为指定的编码
     *
     * @param oldFile      旧的文件
     * @param oldCoding    旧文件编码
     * @param targetFile   目标文件
     * @param targetCoding 目标文件编码
     */
    public static void fileCodingTransition(
            File oldFile, String oldCoding, File targetFile, String targetCoding) {
        try (BufferedReader br =
                     new BufferedReader(
                             new InputStreamReader(Files.newInputStream(oldFile.toPath()), oldCoding));
             BufferedWriter bw =
                     new BufferedWriter(
                             new OutputStreamWriter(
                                     Files.newOutputStream(targetFile.toPath()), targetCoding));) {
            char[] c = new char[1024 * 8];
            int len = 0;
            while ((len = br.read(c)) != -1) {
                bw.write(c, 0, len);
            }
        } catch (Exception e) {
            throw new CommonException(e);
        }
    }

    public static void fileCodingTransition(File oldFile, File targetFile, String targetCoding) {
        String fileCharsetName = getFileCharsetName(oldFile);
       fileCodingTransition(oldFile, fileCharsetName, targetFile, targetCoding);

    }
}
